/* APP，小程序专用组装数据处理中心，*/

import _dispatch from './utils/dispatch';
import { START } from './utils/start';
import { SUCCESS } from './utils/success';
import { FAIL } from './utils/fail';
import getIn from './utils/getIn';
export const STATUS_NORMAL = 0;
export const STATUS_SETTING_LOADING = 1;// 正在获取系统配置
export const STATUS_SETTING_FINISH = 3;
export const STATUS_UPDATE = 4;// 正在更新资料包(快照)
export const STATUS_FINISH = 5;
export const STATUS_NO_SNAPSHOT = 6;
export const STATUS_LOAD_SETTING_FAIL = -1;
export const STATUS_LOAD_SNAPSHOT_FAIL = -2;
import fetchFrontWebSet from './business/setting/fetchFrontWebSet';
import fetchSnapshotDetail from './business/assemble/fetchSnapshotDetail';
import fetchTempletFieldSet from './business/assemble/fetchTempletFieldSet';
// 组装数据装载器，单例模式
const AssembleDataLoader = {
    data: {
        domain: undefined,
        status: STATUS_NORMAL,
        setting: {},
        memory: {},
    },
    // 初始化数据源
    init: function init(params = {}) {
        const {
            actionDispatcher,
            cacheService,
            callback = _dispatch,
            dataFilter = function (d) { return d; },
        } = params;
        this.actionDispatcher = actionDispatcher;
        this.data.initCallback = callback;
        this.cacheService = cacheService;// 注入本地缓存服务；
        this.data.dataFilter = dataFilter;
        this.loading();
    },
    loading() {
        this.actionDispatcher.execute(fetchFrontWebSet, undefined, (f, fetchResult) => {
            if (f === START) {
                this.updateStatus(STATUS_SETTING_LOADING);
            } else if (f === SUCCESS) {
                this.data.setting = fetchResult.data;
                this.updateStatus(STATUS_SETTING_FINISH);
                const n_snapshot_hash = fetchResult.data.snapshot_hash;
                this.validateSnapShot(n_snapshot_hash);
            } else if (f === FAIL) {
                this.updateStatus(STATUS_LOAD_SETTING_FAIL);
            }
        });
    },
    // 对照资料包版本
    validateSnapShot(n_snapshot_hash,isForceUpdate) {
        // 如果没缓存服务，直接用最新的hash去获取数据
        if (!this.cacheService) {
            // 没有hash并且无缓存
            if (!n_snapshot_hash) {
                this.updateStatus(STATUS_NO_SNAPSHOT);
            }
        } else {
            // 检查本地是否有hash吗，判断新旧
            this.cacheService.getCurrentHash((old_snapshot_hash) => {
                if (!n_snapshot_hash && !old_snapshot_hash) { // 没有快照
                    this.updateStatus(STATUS_NO_SNAPSHOT);
                } else if (true || (n_snapshot_hash && !old_snapshot_hash) ) { // 第一次初始化, 加载模板信息
                    this.onLoadSnapShotDetail(n_snapshot_hash,isForceUpdate);
                } else if (n_snapshot_hash && old_snapshot_hash) { // 非第一次初始化
                    if (n_snapshot_hash === old_snapshot_hash) { // 相等则不需要获取快照详情
                        this.updateStatus(STATUS_FINISH);
                    } else { // 不相等则获取最新的
                        this.onLoadSnapShotDetail(n_snapshot_hash);
                    }
                } else if (!n_snapshot_hash && old_snapshot_hash) {
                    this.updateStatus(STATUS_FINISH);
                }
                // 已存在记录，判断是否是最新版本
            });
        }
    },
    getFieldSet(cb) {
        if (this.data.fieldSet) {
            cb && cb(this.data.fieldSet);
        } else if (this.cacheService) {
            this.cacheService.getFieldSet((d) => {
                // this.data.fieldSet = d;
                cb && cb(d);
            });
        }
    },
    getTemplet(cb) {
        if (this.data.templet_id) {
            cb && cb(this.data.templet_id);
        } else if (this.cacheService) {
            this.cacheService.getTemplet((d) => {
                // this.data.templet_id = d;
                cb && cb(d);
            });
        }
    },
    // 获取首页page
    getHomePage: function getHomePage(cb) {
        if (this.data.homePageData) {
            cb && cb(this.data.homePageData);
        } else if (this.cacheService) {
            this.cacheService.getHomePage((d) => {
                // this.data.homePageData = d;
                cb && cb(d);
            });
        }
    },
    // 加载页面相关组装信息，先从内存中找，没有的话，从缓存服务找
    getPage: function loadPage(pageId, cb) {
        const _f = () => {
            this.cacheService && this.cacheService.getPage(pageId, (d) => {
                if (d) {
                    // this.data.memory[pageId] = d;
                }
                cb && cb(d);
            });
        };
        if (!pageId) {
            cb && cb(undefined);
        } else if (this.data.memory[pageId]) {
            cb && cb(this.data.memory[pageId]);
        } else {
            _f();
        }
    },
    // 获取快照详情
    onLoadSnapShotDetail(hash) {
        this.actionDispatcher.execute(fetchSnapshotDetail, { hash }, (f, fetchResult) => {
            if (f === START) {
                this.data.status = STATUS_UPDATE;
            } else if (f === SUCCESS) {
                if (fetchResult && fetchResult.data) {
                  this.actionDispatcher.execute(fetchTempletFieldSet, { templet_id: getIn(fetchResult, ['data', 'templet', 'id']) }, (f, fetchResult) => {
                        if (f === SUCCESS) {
                            this.cacheService && this.cacheService.saveFieldSet(hash, fetchResult.data);
                        }
                    });
                    const filterData = this.data.dataFilter(fetchResult.data);
                    this.cacheService && this.cacheService.saveShotDetail(hash, filterData);
                }
                this.updateStatus(STATUS_FINISH);
            } else {
                this.updateStatus(STATUS_LOAD_SNAPSHOT_FAIL);
            }
        });
    },
    updateStatus: function updateStatus(status) {
        this.data.status = status;
        this.data.initCallback(status);
    },
    clearCache: function clearCache() {
        this.cacheService && this.cacheService.clear();
    },
    getPic: function getPic(path, useDefault = true) {
        const defaultImg = '/image/defaultImg.jpg';
        if (typeof (path) === 'string' && path.length > 0) {
            if (path.indexOf('http:') !== -1 || path.indexOf('https:') !== -1) {
                // 如果是绝对路径，直接返回
                return path;
            }
            // 如果是相对的 拼接返回
            return this.data.setting.qiniu_domain + path;
        }

        return useDefault ? defaultImg : '';
    },
};
export default AssembleDataLoader;
